//
//  LZStatusPictureView.swift
//  Weibo
//
//  Created by lzing on 16/3/25.
//  Copyright © 2016年 lzing. All rights reserved.
//

import UIKit
import SDWebImage

class LZStatusPictureView: UICollectionView {
    
    var reuseIdentifier : String = "ReuseIdentifier"
    
    /// 图片url数组
    var pictureURLs : [NSURL]? {
        didSet {
            // 拿到图片数组后,根据图片数量计算配图宽高
            let size = calculateSize()
            
            // 自己更新宽度与高度
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            // 刷新表格数据
            self.reloadData()
        }
    }
    
    ///  计算大小
    private func calculateSize() -> CGSize {
        layout.itemSize = CGSize(width: LZStatusPictureCellWH, height: LZStatusPictureCellWH)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        // 可选绑定
        let count = pictureURLs?.count ?? 0
        // 没有图片
        if count == 0 {
            layout.itemSize = CGSizeZero
            return CGSizeZero
        }
        // 一张图片,按照原尺寸显示
        if count == 1 {
            // 一张图片默认大小
            var imageSize = CGSize(width: LZStatusPictureCellWH, height: LZStatusPictureCellWH)
            // 获取图片url地址
            let urlString = pictureURLs![0].absoluteString
            // 获取本地图片
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(urlString) {
                // 有图片
                imageSize = image.size
            }
            // 有的图片太小
            if imageSize.width < 40 {
                imageSize.width = 40
            }
            
            // 图片太大
            if imageSize.width > UIScreen.width * 0.5 {
                imageSize.width = UIScreen.width * 0.5
            }
            // 设置图片大小
            layout.itemSize = imageSize
            
            return imageSize
        }
        // 多张图片
        layout.minimumLineSpacing = LZStatusPictureMargin
        layout.minimumInteritemSpacing = LZStatusPictureMargin
        // 默认三列
        var column = LZStatusPictureMaxColumn
        // 当2张图片和4张图片的时候只有2列
        if count == 2 || count == 4 {
            column = 2
        }
        // 计算总行数
        let row = (count + column - 1) / column
        // 计算宽度
        let width = LZStatusPictureCellWH * CGFloat(column) + (CGFloat(column) - 1) * LZStatusPictureMargin
        // 计算高度
        let height = LZStatusPictureCellWH * CGFloat(row) + (CGFloat(row) - 1) * LZStatusPictureMargin
        
        return CGSize(width: width, height: height)
    }
    
    private let layout = UICollectionViewFlowLayout()

    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        // 禁用滚动到顶部
        scrollsToTop = false
        // 设置数据源
        dataSource = self
        // 注册cell
        registerClass(LZStatusPictureViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        backgroundColor = UIColor.clearColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension LZStatusPictureView : UICollectionViewDataSource {
    ///  item个数
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLs?.count ?? 0
    }
    ///   cell个数
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView .dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! LZStatusPictureViewCell
        
        cell.imageURL = pictureURLs?[indexPath.item]
        
        return cell
    }
}

// MAKR: - CZStatusPictureViewCell
class LZStatusPictureViewCell : UICollectionViewCell {
    // MARK: - 属性
    var imageURL : NSURL? {
        didSet {
            if let url = imageURL {
                backgroundImageView.sd_setImageWithURL(url)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 添加子控件
        addSubview()
        // 添加约束
        addConstraint()
        // 设置填充模式
        backgroundImageView.contentMode = UIViewContentMode.ScaleAspectFill
        // 超出图片裁剪
        backgroundImageView.clipsToBounds = true
    }
    // 添加子控件
    private func addSubview() {
        contentView.addSubview(backgroundImageView)
    }
    // 添加约束
    private func addConstraint() {
        backgroundImageView.snp_makeConstraints { (make) -> Void in
          make.edges.equalTo(contentView)
        };
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - lazy
    private lazy var backgroundImageView :UIImageView = UIImageView()
}
